package com.imxinxin.common.tools.io;


import java.io.*;

/**
 * @Author: XYX
 * @Date: 2019/12/20
 * @Description:
 */
public class InputStreamTool {

    //处理InputStream的最大内存申请
    public final static int MAX_BYTE = 8 * 1024 * 1024;

    /**
     * 读取数据为String 不适用大数据读取
     *
     * @param in
     * @param charset
     * @return
     * @throws IOException
     */
    public static String inputStreamToString(InputStream in, String charset) throws IOException {
        byte[] bytes = inputStreamToBytes(in);
        if (bytes == null) {
            return null;
        }
        return new String(bytes, charset);
    }

    /**
     * 输入流中读取数据到byte[]中
     * 注意不适用大数据读取 会导致内存过高
     *
     * @param in
     * @return
     */
    public static byte[] inputStreamToBytes(InputStream in) throws IOException {
        if (in == null) {
            return null;
        }

        byte[] bytes = new byte[8192];
        ByteArrayOutputStream out = null;
        try {
            int i = in.read(bytes);
            out = new ByteArrayOutputStream();
            while (i != -1) {
                if (out.size() > MAX_BYTE) {
                    throw new IOException("请求接口数据不得超过8M,防止内存溢出中止读取数据,大文件请使用file方法");
                }
                out.write(bytes, 0, i);
                i = in.read(bytes);
            }
            return out.toByteArray();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } finally {
                in.close();
            }
        }

    }

    /**
     * 将输入流的数据写入到文件中去
     *
     * @param in
     * @param filePath
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String inputStreamToFile(InputStream in, String filePath, String fileName) throws IOException {

        if (in == null) {
            return null;
        }

        if (fileName == null || fileName.trim().equals("")) {
            return null;
        }
        if (filePath == null) {
            filePath = "";
        }

        File fileD = new File(filePath);
        if (!fileD.exists()) {
            fileD.mkdirs();
        }


        if (!filePath.endsWith("/") && !"".equals(filePath)) {
            filePath = filePath + "/";
        }

        File file = new File(filePath + fileName);

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            byte[] bytes = new byte[8192];
            int i = in.read(bytes);
            while (i != -1) {
                out.write(bytes, 0, i);
                i = in.read(bytes);
            }
        } catch (Exception e) {
            file.deleteOnExit();
            throw e;
        } finally {
            try {
                in.close();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
        return file.getPath();
    }


}
